package cn.campsg.messageboard.controller;

import cn.campsg.messageboard.dao.UserDao;
import cn.campsg.messageboard.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login") // 确保Servlet能被正确映射
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        UserDao userDao = new UserDao();
        boolean valid = userDao.validateUser(username, password);

        if (valid) {
            User user = userDao.getUserByUsername(username);
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            session.setAttribute("user", user);
            request.getSession().setAttribute("user", user); // 存入完整User对象
            session.setAttribute("userId", userDao.getUserIdByUsername(username));
            response.sendRedirect("index.jsp");

        } else {
            request.setAttribute("error", "用户名或密码错误。");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}